package com.blue.tooth.lock;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.AnimationDrawable;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;

import com.blue.tooth.lock.adapter.BlueToothDeviceAdapter;
import com.blue.tooth.lock.dialog.CustomAlertDialog;
import com.blue.tooth.lock.util.AppCache;
import com.blue.tooth.lock.util.BleUtil;
import com.blue.tooth.lock.util.DebugLogUtil;
import com.blue.tooth.lock.util.PermissionUtil;
import com.blue.tooth.lock.vo.BlueToothDeviceVo;
import com.meihua.passivelock.BLEConnectCallback;
import com.meihua.passivelock.BLESearchCallBack;
import com.meihua.passivelock.BLETools;
import com.meihua.passivelock.fastble.BleManager;
import com.meihua.passivelock.fastble.data.BleDevice;

import java.util.ArrayList;
import java.util.List;

/**
 * 蓝牙设备列表
 */
public class MainActivity extends Activity implements BLESearchCallBack, View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_device_list);
        mContext = this;
        bluetoothTv = findViewById(R.id.bluetoothTv);
        btn_cancel = findViewById(R.id.btn_cancel);
        btn_disconnect = findViewById(R.id.btn_disconnect);
        bluetoothLog = findViewById(R.id.bluetoothLog);
        bluetoothIv = findViewById(R.id.bluetoothIv);
        iv_running = findViewById(R.id.iv_running);
        listDevice = findViewById(R.id.listDevice);
        userId = findViewById(R.id.userId);
        this.buildData();
        this.buildListener();
        PermissionUtil.openPermission(this, PermissionUtil.APPPERMISSION);
        bluetoothIv.performClick();
    }


    /**
     * 用户选择权限的监听回调
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        for (int i = 0; i < grantResults.length; i++) {
            boolean isTip = ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[i]);
            if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(mContext, "请在设置里，打开定位权限，不然无法扫描到蓝牙设备", Toast.LENGTH_LONG);
                if (isTip) {
                    //表明用户没有彻底禁止弹出权限请求
//                    PermissionUtil.openPermission(this, permissions[i]);
                } else {
                    //表明用户已经彻底禁止弹出权限请求
                }
                return;
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        boolean isOpenGps = this.isOpenGps(getApplicationContext());
        boolean isOpenBluetooth = this.isOpenBluetooth();
        if (!isOpenGps) {
            showBlutoothTipDialog(1, "您手机未打开GPS，请先打开GPS.");
        } else if (!isOpenBluetooth) {
            showBlutoothTipDialog(2, "您手机未打开蓝牙，请先打开蓝牙.");
        }
        allConnectedDevice = BleManager.getInstance().getAllConnectedDevice();
        if (allConnectedDevice != null && allConnectedDevice.size() > 0) {
            btn_disconnect.setVisibility(View.VISIBLE);
            BluetoothDevice device = allConnectedDevice.get(0).getDevice();
            BlueToothDeviceVo blueToothDeviceVo = new BlueToothDeviceVo();
            String name = device.getName();
            if (name != null && name.startsWith("HZMH")) {
                data = new ArrayList<>();
                blueToothDeviceVo.setMac(device.getAddress());
                name = getPrivateName(name);

                blueToothDeviceVo.setName(name);//HZMH-0100FF7791539409FFFF
                blueToothDeviceVo.setBleDevice(blueToothDeviceVo.getBleDevice());
                data.add(blueToothDeviceVo);
                bluetoothAdapter.setData(data);
                bluetoothAdapter.notifyDataSetChanged();
                DebugLogUtil.getInstance().Debug("目前连接：" + name);//+ allConnectedDevice.get(0).getDevice().getName()
            }
        }
    }

    private boolean isOpenBluetooth() {
        BluetoothAdapter blueadapter = BluetoothAdapter.getDefaultAdapter();
        if (!blueadapter.isEnabled()) {
            return false;
        }
        return true;
    }

    /**
     * 判断GPS是否开启，GPS或者AGPS开启一个就认为是开启的
     *
     * @param context
     * @return true 表示开启
     */
    private boolean isOpenGps(Context context) {
        LocationManager locationManager
                = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        // 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        // 通过WLAN或移动网络(3G/2G)确定的位置（也称作AGPS，辅助GPS定位。主要用于在室内或遮盖物（建筑群或茂密的深林等）密集的地方定位）
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || network) {
            return true;
        }
        return false;
    }

    private void showBlutoothTipDialog(final int code, final String message) {
        final CustomAlertDialog customAlertDialog = new CustomAlertDialog(mContext);
        customAlertDialog.setMessage(message);
        customAlertDialog.setNegativeButton(R.id.submit_butt, "确定", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                customAlertDialog.dismiss();
                if (code == 1) {
                    openSystemSetActivity();
                } else if (code == 2) {
                    startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS));
                }
            }
        }, View.VISIBLE);
        customAlertDialog.setNegativeButton(R.id.cancel_butt, "取消", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                customAlertDialog.dismiss();
            }
        }, View.VISIBLE);
    }

    private void openSystemSetActivity() {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        try {
            startActivity(intent);
        } catch (ActivityNotFoundException ex) {
            intent.setAction(Settings.ACTION_SETTINGS);
            try {
                startActivity(intent);
            } catch (Exception e) {
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_disconnect:
                data = new ArrayList<>();
                Intent i = new Intent(this, ConnectKeyAct.class);
                i.putExtra("isAutoConnect", false);
                i.putExtra("opt", false);//opt :true  连接 false 断开
                setResult(Activity.RESULT_OK, i);
                finish();
                break;
            case R.id.btn_cancel:
                finish();
                break;
            case R.id.bluetoothIv:
                if (isOpen) {
//                    broccoli.clearAllPlaceholders();
                    bluetoothIv.setImageResource(R.drawable.switch_off);
                    closeBlueTooth();
                } else {
                    bluetoothLog.setText("");
                    bluetoothIv.setImageResource(R.drawable.switch_on);
                    scan();
//                    broccoli.show();
                }
                isOpen = !isOpen;
                break;
            default:
                break;
        }
    }

    private void buildData() {
        data = new ArrayList<>();
        bluetoothAdapter = new BlueToothDeviceAdapter(data, mContext);
        listDevice.setAdapter(bluetoothAdapter);
    }

    private BLETools getBleTools() {
        if (bleTools == null) {
            bleTools = new BLETools();
        }
        return bleTools;
    }

    private void buildListener() {
        bluetoothIv.setOnClickListener(this);
        btn_cancel.setOnClickListener(this);
        btn_disconnect.setOnClickListener(this);
        listDevice.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                BlueToothDeviceVo blueToothDeviceVo = data.get(position);
                Intent intent = new Intent(mContext, ConnectKeyAct.class);
                intent.putExtra("isAutoConnect", true);
                Bundle bundle = new Bundle();
                bundle.putString("mac", blueToothDeviceVo.getMac());
                bundle.putString("name", blueToothDeviceVo.getName());
                AppCache.setBleDevice(blueToothDeviceVo.getBleDevice());
                intent.putExtras(bundle);
                setResult(Activity.RESULT_OK, intent);
                finish();
            }
        });

        getBleTools().setBleCallBack(this);

    }

    //开始扫描蓝牙锁
    private void scan() {
        isScan = true;
        this.startScanAnim();

        getBleTools().bleInit(this.getApplication());
    }

    private void startScanAnim() {
        iv_running.setVisibility(View.VISIBLE);
        anim = (AnimationDrawable) iv_running.getDrawable();
        iv_running.post(new Runnable() {
            @Override
            public void run() {
                anim.start();
            }
        });
    }

    private void closeBlueTooth() {
        if (isScan && BleManager.getInstance() != null) {
            BleManager.getInstance().cancelScan();
        }
        DebugLogUtil.getInstance().Debug("地址2=" + getBleTools().toString());
        getBleTools().disConnect();

        data.clear();
        bluetoothAdapter.notifyDataSetChanged();
    }


    /**
     * @param success 本次扫描动作是否开启成功
     */
    @Override
    public void onBleScanStarted(boolean success) {
        if (success) {
            bluetoothLog.setText("正在扫描设备.");
        } else {
            bluetoothLog.setText("扫描开启失败");
        }
    }

    /**
     * 扫描到一个设备,bleDevice包含name,mac等参数，name有可能为空
     */
    @Override
    public void onBleScanning(BleDevice bleDevice) {
        Log.i(TAG, "onBleScanning:" + bleDevice.getName() + "," + bleDevice.getMac() + "," + bleDevice.getScanRecord());
        //目前只处理名称以 HZMH 开关的锁
        if (bleDevice != null) {//&& bleDevice.getName().startsWith("HZMH")
            BlueToothDeviceVo blueToothDeviceVo = new BlueToothDeviceVo();
            String name = bleDevice.getName();
            if (name == null) {
                name = BleUtil.parseAdertisedData(bleDevice.getScanRecord()).getName();
            }
            if (name != null && name.startsWith("HZMH")) {
                blueToothDeviceVo.setMac(bleDevice.getMac());
                name = getPrivateName(name);
                blueToothDeviceVo.setName(name);//HZMH-0100FF7791539409FFFF
                blueToothDeviceVo.setBleDevice(bleDevice);
                data.add(blueToothDeviceVo);
                bluetoothAdapter.setData(data);
                bluetoothAdapter.notifyDataSetChanged();
            }

        }
    }

    private String getPrivateName(String wholeName) {
        String name = "";
        if (wholeName.length() > 9) {
//            name = wholeName.substring(5, 11);
            name = wholeName.substring(5);
        }
        return name;
    }

    /**
     * 扫描完成
     *
     * @param scanResultList 本次扫描到的所有设备
     */
    @Override
    public void onBleScanFinished(List<BleDevice> scanResultList) {
        anim.stop();
        iv_running.setVisibility(View.GONE);
        isScan = false;
        if (data.size() == 0) {
            bluetoothLog.setText("未扫描到可用设备");
        } else {
            bluetoothLog.setText("共扫描到" + data.size() + "个设备");
        }
    }


    private Button btn_cancel, btn_disconnect;
    private TextView bluetoothTv;
    private TextView bluetoothLog;
    private ImageView bluetoothIv;
    private ImageView iv_running;
    private ListView listDevice;
    private EditText userId;
    //蓝牙相关
    private BLETools bleTools;

    private List<BlueToothDeviceVo> data;
    private List<BleDevice> allConnectedDevice;
    private BlueToothDeviceAdapter bluetoothAdapter;
    private Context mContext;
    private boolean isOpen;//蓝牙打开状态
    private boolean isScan;//是否正在扫描
    private AnimationDrawable anim;

    private final String TAG = "MainActivity";
    private static final int REQUEST_ENABLE_BT = 2;
}
